package com.sunjob.loginserver.config;

import cn.dev33.satoken.dao.SaTokenDaoRedisJackson;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.sunjob.common.constant.MROConstant;
import com.sunjob.common.domain.loginServer.SysMenu;
import com.sunjob.common.domain.loginServer.SysRole;
import com.sunjob.loginserver.service.MenuService;
import com.sunjob.loginserver.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.dev33.satoken.dao.SaTokenDaoRedisJackson;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-07-26 14:17
 */
@Component
@Slf4j
public class RoleAndAuthConfig implements StpInterface {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        HashOperations<String, String, List<String>> hashOperations = redisTemplate.opsForHash();
        HashOperations<String, String, SysMenu> hashOperations1 = redisTemplate.opsForHash();
        // 获取用户角色列表
        List<String> o = hashOperations.get(MROConstant.USER_ROLES, loginId + "");
        // 获取权限列表
        List<String> res = new ArrayList<>();
        o.stream().forEach(e->{
            // 尝试从缓存中获取
            List<String> menus = hashOperations.get(MROConstant.ROLE_MENUS, e);
            res.addAll(menus);
        });
        // 返回权限列表
        List<SysMenu> menu_res = hashOperations1.multiGet(MROConstant.MENUS, res);
        return menu_res.stream().map(e->e.getPerms()).collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 尝试从redis缓存中获取
        HashOperations<String, String, SysRole> hashOperations = redisTemplate.opsForHash();
        HashOperations<String, String, List<String>> hashOperations1 = redisTemplate.opsForHash();
        Object o = hashOperations1.get(MROConstant.USER_ROLES, loginId);
        if (o == null) {
            // 刷入缓存
            List<String> roles = roleService.queryRoleIdByLoginId(Long.valueOf((String) loginId));
            // 用户id 映射 角色id列表
            hashOperations1.put(MROConstant.USER_ROLES, loginId + "", roles);
            o = roles;
        }
        List<SysRole> list = (hashOperations.multiGet(MROConstant.ROLES,(List<String>)o));
        return list.stream().map(e->e.getRoleKey()).collect(Collectors.toList());
    }
}
